package com.ruoyi.site.service.impl;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.*;
import com.ruoyi.site.service.IMailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SESMailServiceImpl implements IMailService {

    @Value("${aws.region}")
    private String awsRegion;

    @Value("${aws.accessKey}")
    private String awsAccessKey;

    @Value("${aws.secretKey}")
    private String awsSecretKey;

    @Value("${aws.ses.fromEmail}")
    private String fromEmail;

    private AmazonSimpleEmailService client;

    private AmazonSimpleEmailService getClient() {
        if (client == null) {
            BasicAWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
            client = AmazonSimpleEmailServiceClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(credentials))
                    .withRegion(Regions.fromName(awsRegion))
                    .build();
        }
        return client;
    }

    @Override
    public void sendVerificationEmail(String toEmail, String verificationUrl) {
        String subject = "Verscape: Please Verify Your Email Address";
        String htmlBody = String.format(
                "<h1>Welcome to Verscape!</h1>" +
                        "<p>Click the link below to verify your email and activate your account:</p>" +
                        "<a href=\"%s\">Verify Email</a>" +
                        "<p>If you did not sign up for Verscape, please ignore this email.</p>",
                verificationUrl
        );

        SendEmailRequest request = new SendEmailRequest()
                .withDestination(new Destination().withToAddresses(toEmail))
                .withMessage(new Message()
                        .withBody(new Body().withHtml(new Content().withCharset("UTF-8").withData(htmlBody)))
                        .withSubject(new Content().withCharset("UTF-8").withData(subject)))
                .withSource(fromEmail);

        try {
            getClient().sendEmail(request);
            // 记录日志：邮件发送成功
        } catch (Exception ex) {
            // 记录日志：邮件发送失败，并抛出自定义异常
            throw new RuntimeException("无法发送验证邮件到 " + toEmail + "：" + ex.getMessage());
        }
    }
}